<?php
header("server-ip:".$_SERVER["SERVER_ADDR"]);
header("server-name:".substr(php_uname(), 0, 20));
/*
 *@自动加载类库
 *@author usual2970
 */
function __autoload($class){

	$class_temp=strtolower($class);
	if($class=="_smarty_template_buffer"){
		require_once(UPATH."/library/smarty/sysplugins/smarty_internal_compile_function.php");
		return false;
	}
	$file=UPATH."/library/".$class_temp.".php";
	if(file_exists($file)){ 
		require_once($file);
		return false;
	}
	elseif(file_exists(UPATH."/library/smarty/".$class.".class.php")){
		require_once(UPATH."/library/smarty/".$class.".class.php");
		return false;

	}
	elseif(file_exists(UPATH."/library/smarty/sysplugins/".$class_temp.".php")){
		require_once(UPATH."/library/smarty/sysplugins/".$class_temp.".php");
		return false;
	}
	var_dump($class);
	Umsg("调用的类不存在");
	
	

}
/**
 * 获得用户的真实IP地址
 *
 * @return  string
 */
function real_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}


/**
 * 获得当前格林威治时间的时间戳
 *
 * @return  integer
 */
function gmtime()
{
    return (time() - date('Z'));
}

/*
 *@加载配置
 *@author usual2970
 */
function load_conf($config){
	$config=strtolower($config);
	if(isset($GLOBALS["conf"]) && $GLOBALS["conf"][$config]){
		return $GLOBALS["conf"][$config];
	}
		
	$file=UPATH."/data/config/".$config.".cfg.php";
	$conf=array();
	if(!file_exists($file)) return false;
	require($file);
	return $conf;
}

/*
 *@加载控制器文件
 *@author usual2970
 */
function load_control($control){
	$control=strtolower($control);
	$file=UPATH."/app/control/".$control.".ctrl.php";
	if(!file_exists($file)) Umsg("控制器文件不存在".$file);
	require_once($file);
}

/*
 *@加载模型
 *@author usual2970
 */
function load_model($model){
	$model=strtolower($model);
	$file=UPATH."/app/model/".$model.".model.php";
	if(!file_exists($file)) Umsg("模型不存在");
	require_once($file);
}

/*
 *@调用某个模型的方法
 */
function modcall($model,$func,$args){
	load_model($model);
	$class=ucfirst($model)."Model";
	if(!class_exists($class)){
		Umsg("模型无效");
	}
	
	$rs=BaseCall("ctl",$class,$func,$args);
	return $rs;
}

/*
 *@加载dao
 *@author usual2970
 */
function load_dao($dao){
	$model=strtolower($dao);
	$file=UPATH."/app/dao/".$dao.".dao.php";
	if(!file_exists($file)) Umsg("DAO文件".$file."不存在");
	require_once($file);
}

/*
 *@调用某个DAO的方法
 */
function daocall($dao,$func,$args){
	load_dao($dao);
	$class=ucfirst($dao)."Dao";
	if(!class_exists($class)){
		Umsg("Dao:".$dao."无效");
	}
	
	$rs=BaseCall("ctl",$class,$func,$args);
	return $rs;
}
/*
 *@调用方法最底层
 */
function BaseCall($module,$className,$method,$args) {
	$object	= $module == 'ctl' ? new $className : $className;
	if($object && method_exists($object, $method))
	{
		$result = call_user_func_array(array($object, $method), $args);
	
		return $result;
	} else {
		return false;
	}
}
/*
 *@加载视图
 */
 function load_view($__file, $__data = null, $__print = true){
        
	

	!defined("__OUTVIEW__") && define("__OUTVIEW__", 1);
	if(!is_null($__data))
	{
		if(is_array($__data))
		{
			foreach ($__data as $__key => $__value)
			{
				if (!isset($$__key) )
				{
					$$__key = $__value;
				}
			}
		}
		else if(is_object($__data))		//将类属性转化为变量
		{
			$__data = get_object_vars($__data);
		}
		else
		{
			trigger_error(__FUNCTION__ . ' 函数的第2个参数必须是数组或者类', E_USER_NOTICE);
		}
	}

	$file=UPATH."/app/view/".$__file.".view.php";
	if(!file_exists($file)) Umsg("视图不存在");
	ob_start();
	require_once($file);
	$__ob_content = ob_get_contents();
	ob_end_clean();

	if($__print)
	{
		if(isset($GLOBALS["cookie"]) && $GLOBALS["cookie"])
		{
			header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
			//header('P3P: CP="NOI DEV PSA PSD IVA PVD OTP OUR OTR IND OTC"');
			foreach($GLOBALS["cookie"] as $cn => $cv)
			{
				@setcookie($cn, $cv["value"], $cv["expire"], $cv["path"], $cv["domain"]);
			}
		}
		unset($GLOBALS["cookie"]);
		
		header("Content-type:text/html;charset=utf-8");
		echo $__ob_content;
	} else return $__ob_content;
 }

 /**
 * 获得当前的域名
 *
 * @return  string
 */
function get_domain()
{
    /* 协议 */
    $protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';

    /* 域名或IP地址 */
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
    {
        $host = $_SERVER['HTTP_X_FORWARDED_HOST'];
    }
    elseif (isset($_SERVER['HTTP_HOST']))
    {
        $host = $_SERVER['HTTP_HOST'];
    }
    else
    {
        /* 端口 */
        if (isset($_SERVER['SERVER_PORT']))
        {
            $port = ':' . $_SERVER['SERVER_PORT'];

            if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
            {
                $port = '';
            }
        }
        else
        {
            $port = '';
        }

        if (isset($_SERVER['SERVER_NAME']))
        {
            $host = $_SERVER['SERVER_NAME'] . $port;
        }
        elseif (isset($_SERVER['SERVER_ADDR']))
        {
            $host = $_SERVER['SERVER_ADDR'] . $port;
        }
    }

    return $protocol . $host;
}

/**
 * 获得网站的URL地址
 *
 * @return  string
 */
function site_url()
{
	$php_self=htmlentities(isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
    return get_domain() . substr($php_self, 0, strrpos($php_self, '/'));
}


/**
 * @显示系统信息
 *
 * @param string $msg 信息
 * @param string $url 返回地址
 * @param boolean $isAutoGo 是否自动返回 true false
 */
function Umsg($msg, $url='javascript:history.back(-1);', $isAutoGo=false){
	if ($msg == '404') {
		header("HTTP/1.1 404 Not Found");
		$msg = '抱歉，你所请求的页面不存在！';
	}
	echo <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
EOT;
	if($isAutoGo){
		echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\" />";
	}
	echo <<<EOT
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>emlog system message</title>
<style type="text/css">
<!--
body {
	background-color:#F7F7F7;
	font-family: Arial;
	font-size: 12px;
	line-height:150%;
}
.main {
	background-color:#FFFFFF;
	font-size: 12px;
	color: #666666;
	width:650px;
	margin:60px auto 0px;
	border-radius: 10px;
	padding:30px 10px;
	list-style:none;
	border:#DFDFDF 1px solid;
}
.main p {
	line-height: 18px;
	margin: 5px 20px;
}
-->
</style>
</head>
<body>
<div class="main">
<p>$msg</p>
<p><a href="$url">&laquo;点击返回</a></p>
</div>
</body>
</html>
EOT;
	exit;
}

function us_mkdir($absolute_path, $mode = 0777)
{
    if (is_dir($absolute_path))
    {
        return true;
    }

    $root_path      = UPATH;
    $relative_path  = str_replace($root_path, '', $absolute_path);
    $each_path      = explode('/', $relative_path);
    $cur_path       = $root_path; // 当前循环处理的路径
    foreach ($each_path as $path)
    {
        if ($path)
        {
            $cur_path = $cur_path . '/' . $path;
            if (!is_dir($cur_path))
            {
                if (@mkdir($cur_path, $mode))
                {
                    fclose(fopen($cur_path . '/index.htm', 'w'));
                }
                else
                {
                    return false;
                }
            }
        }
    }

    return true;
}
//格式化手机号码
function phone_star($phone){
	return preg_replace("/^(\d{3})\d{4}(\d{4})$/", "$1****$2", $phone);
}
//写日志
function cdlog($str,$display_errors=false,$forceWrite=false)
{
	global $starttime;
	$recordTime=myTime();
	$expend=$recordTime-$starttime;
	$request_slow=0.00001;
	$request_slow?"":$request_slow=1;
	$request_slow=(float)$request_slow;
	$starttime=$recordTime;
	$expend=intval($expend*100000)/100000;
	if($request_slow<$expend||$forceWrite)
	{
		if($expend>1)
		{
			if($expend>3)
			{
				$expend="<font color=red>{$expend}</font>";
			}
			else
			{
				$expend="<font color=#F7A248>{$expend}</font>";
			}
		}
	}
	else
	{
		if(!isset($_GET['debug']) && !$_COOKIE['debug'])
		{
			return;
		}
	}

	$log = UPATH."/data/logs/paylog/access.log";
	if (is_file($log))
	{
		if (filesize($log) > 500 * 1024)
		{
			$log2 = str_replace(".log", "_".date("Ymd H-i").".log", $log);@rename($log, $log2);
		}
	}
	$error_str="^".date("Y-m-d H:i:s")." | ".substr(php_uname(), 0, 20)." | ".($expend>0?"耗时".$expend:"")." | ".$str." <br>访问:<font color=blue>http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."</font> <br>来源:<font color=green>".$_SERVER['HTTP_REFERER']."</font>(".real_ip().")\$\n";
	if(isset($_GET['debug']))
	{
		var_dump($error_str);
	}
	else 
	{   // $G_SHOP = isset($G_SHOP) ? $G_SHOP : '';
		//if($G_SHOP){
		//$G_SHOP->DBCA->query("INSERT INTO tcz_log(starttime,exetime,url)values(".time().",$expend,'".addslashes($str)."')");
		//}
		file_put_contents($log, $error_str, FILE_APPEND);
	}
	
}

//开始运行时间，用作性能调试。
function myTime()
{
	$pageStart=explode(' ', microtime());
	return $pageStart[1] + $pageStart[0];
}

function tcz_fopen($url, $limit = 500000, $post = '', $cookie = '', $bysocket = false, $ip = '', $timeout = 300, $block = true){

    $return = '';
    $matches = parse_url($url);

    $host = $matches['host'];
    if(isset($matches['query'])){
    	$strQuery=$matches['query'];
    }else{
    	$strQuery='';
    }
    $path = $matches['path'] ? $matches['path'].($strQuery ? '?'.$strQuery : '') : '/';
    $port = !empty($matches['port']) ? $matches['port'] : 80;

    if($post)
    {
        $out = "POST $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
        //$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: UTF-8\r\n";
        $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= 'Content-Length: '.strlen($post)."\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Cache-Control: no-cache\r\n";
        $out .= "Cookie: $cookie\r\n\r\n";
        $out .= $post;
    }
    else
    {
        $out = "GET $path HTTP/1.0\r\n";
        $out .= "Accept: */*\r\n";
        //$out .= "Referer: $boardurl\r\n";
        $out .= "Accept-Language: UTF-8\r\n";
        $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Cookie: $cookie\r\n\r\n";
    }
    $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
    if(!$fp)
    {
        return '';
    }
    else
    {
        stream_set_blocking($fp, $block);
        stream_set_timeout($fp, $timeout);
        @fwrite($fp, $out);
        $status = stream_get_meta_data($fp);
        if(!$status['timed_out'])
        {
            while (!feof($fp))
            {
                if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n"))
                {
                    break;
                }
            }

            $stop = false;
            while(!feof($fp) && !$stop)
            {
                $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
                $return .= $data;
                if($limit)
                {
                    $limit -= strlen($data);
                    $stop = $limit <= 0;
                }
            }
        }
        @fclose($fp);
        return $return;
    }
}